package com.java2nb.novel.utils;


import okhttp3.*;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;
import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 * OkHttp3客户端工具类（单例，连接池）
 */
@Component
public class OkHttpUtils {

    private OkHttpClient okHttpClient;
    /** 连接超时时间（ms） */
    @Value("${pay.gateway.connect-timeout}")
    private int connectTimeout;

    /** 读取超时时间（ms） */
    @Value("${pay.gateway.read-timeout}")
    private int readTimeout;

    /**
     * 初始化OkHttpClient（单例，连接池）
     */
    @PostConstruct
    public void init() {
        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(connectTimeout, java.util.concurrent.TimeUnit.MILLISECONDS)
                .readTimeout(readTimeout, java.util.concurrent.TimeUnit.MILLISECONDS)
                .connectionPool(new ConnectionPool(50, 300, java.util.concurrent.TimeUnit.SECONDS)) // 连接池：50个最大空闲连接，存活300s
                .build();
    }

    /**
     * 发送POST请求（JSON格式）
     * @param url 请求URL
     * @param jsonParams JSON参数
     * @return 响应字符串
     * @throws IOException 网络异常
     */
    public String postJson(String url, String jsonParams) throws IOException {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonParams, mediaType);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = okHttpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("支付网关请求失败，响应码：" + response.code());
            }
            return response.body().string();
        }
    }
}
